/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/**
 * 流量主广告添加、编辑弹窗
 *  */
import React, { useState, useEffect } from "react";
import { Modal, Form, Checkbox, Input, Radio } from "antd";
import { useSelector, useDispatch } from "dva";

const initPositionOptions = [
  { label: "查件页", value: "check_piece_page", disabled: false },
  { label: "物流详情页", value: "logistics_details_page", disabled: true },
  { label: "预约取件页", value: "subscribe_get_page", disabled: false },
  { label: "订单提交页", value: "order_submit_page", disabled: false },
  { label: "驿站主页", value: "stage_home_page", disabled: false },
  { label: "订单详情页", value: "order_details_page", disabled: false },
];

const advTypes = [
  { label: "banner广告", value: "1" },
  { label: "插屏广告", value: "2" },
  // { label: "福利广告", value: "3" },
];

const FormItem = Form.Item;
const formItemLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const MiniAdvAdd = ({ visible, onClose, refreshParent, form, type = "add", record = {} }) => {
  const { getFieldDecorator, resetFields, validateFields } = form;
  const { type: adv_type, position: adv_pos, ad_id, id } = record;

  const dispatch = useDispatch();
  // 已设置的自定义小程序广告位
  const { mini_app_checkBox = [], selectedPostAdv = [], selectedWelfareAdv = [] } = useSelector(
    ({ wxSettings }) => wxSettings.advSetting
  );

  const [positionOptions, setPositionOptions] = useState(initPositionOptions);

  const onSubmit = () => {
    validateFields((err, values) => {
      if (err) return;
      const { adv_type, position, ad_id } = values;
      const payload = {
        id,
        type: adv_type,
        ad_id,
        position: JSON.stringify(position),
      };
      dispatch({
        type: "wxSettings/setMiniAdv",
        payload,
      }).then(() => {
        onClose && onClose();
        refreshParent && refreshParent();
      });
    });
  };

  const onCancel = () => {
    onClose && onClose();
  };

  /** 更新checkBox的初始值 */
  const updateCheckBoxInitValue = (disabled = false, checkedValue = []) => {
    setPositionOptions(prevState => {
      prevState.forEach(val => {
        if (disabled) {
          if (checkedValue.includes(val.value)) {
            val.disabled = true;
          } else {
            val.disabled = false;
          }
        } else {
          val.disabled = false;
        }
      });
      return prevState;
    });
  };

  /** 广告类型选择 */
  const onTypeChange = e => {
    const { value } = e.target;
    // 插屏广告，福利广告切换
    if (value == 1) {
      updateCheckBoxInitValue(true, [...mini_app_checkBox.filter(v => v != "check_piece_page")]);
    } else if (value == 2) {
      // 插屏广告
      updateCheckBoxInitValue(true, selectedWelfareAdv);
    } else if (value == 3) {
      // 福利广告
      updateCheckBoxInitValue(true, selectedPostAdv);
    }
  };

  useEffect(
    () => {
      if (visible) {
        if (adv_type == 1 || type == "add") {
          updateCheckBoxInitValue(true, [
            ...mini_app_checkBox.filter(v => v != "check_piece_page"),
          ]);
        }
        if (adv_type == 2) {
          updateCheckBoxInitValue(true, selectedWelfareAdv);
        }
        if (adv_type == 3) {
          updateCheckBoxInitValue(true, selectedPostAdv);
        }
      } else {
        setPositionOptions(initPositionOptions);
        updateCheckBoxInitValue(false);
        resetFields();
      }
    },
    [visible, type, adv_type]
  );

  return (
    <Modal
      width={800}
      title={type === "add" ? "添加广告" : "编辑广告"}
      visible={visible}
      onOk={onSubmit}
      onCancel={onCancel}
      destroyOnClose
    >
      <Form {...formItemLayout}>
        <FormItem label="选择广告类型">
          {getFieldDecorator("adv_type", {
            initialValue: adv_type || "1",
          })(<Radio.Group onChange={onTypeChange} options={advTypes} />)}
        </FormItem>
        <FormItem label="广告ID">
          {getFieldDecorator("ad_id", {
            initialValue: ad_id,
            rules: [
              {
                required: true,
                message: "请输入广告ID",
              },
            ],
          })(<Input allowClear style={{ width: 290 }} placeholder="请输入广告ID" />)}
        </FormItem>
        <FormItem label="广告开启位置">
          {getFieldDecorator("position", {
            initialValue: adv_pos || [],
            rules: [
              {
                required: true,
                message: "请选择广告位",
              },
            ],
          })(<Checkbox.Group options={positionOptions} />)}
        </FormItem>
      </Form>
    </Modal>
  );
};

export default Form.create({
  onValuesChange: (props, changedValues) => {
    const { form } = props;
    const { setFieldsValue } = form;
    const { adv_type } = changedValues;
    if (adv_type) {
      setFieldsValue({
        position: [],
      });
    }
  },
})(MiniAdvAdd);
